# Produce lists of winner and loser parties and candidates analyzed in the study.
# See Appendix C.




#############
# load data #
#############

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)
library(dplyr)

load("PSRM Replication Files/PresidentialElectionsPosts.RData")

colnames(president_df)

length(unique(president_df$country)) # 26
length(unique(president_df$electionname)) # 29
length(unique(president_df$party_country)) # 52

# focus on 15 days before and after the election
day_range <- 15

sub <- president_df[which(president_df$daysinceelection >= -1*day_range
                          & president_df$daysinceelection <= day_range),]

# winners and losers
winners <- sub[which(sub$win == 1),]
losers <- sub[which(sub$win != 1),]

length(unique(winners$electionname[which(!is.na(winners$polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$economic_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$social_polarization))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_present))])) # 27
length(unique(winners$electionname[which(!is.na(winners$populist_dummy))])) # 27

length(unique(losers$electionname[which(!is.na(losers$polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$economic_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$social_polarization))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_present))])) # 27
length(unique(losers$electionname[which(!is.na(losers$populist_dummy))])) # 27




##########################
# elections/parties list #
##########################

winners2 <- unique(winners[,c("electionname", "party", "candidate")])
colnames(winners2)[2:3] <- c("winner_party", "winner_candidate")

losers2 <- unique(losers[,c("electionname", "party", "candidate")])
colnames(losers2)[2:3] <- c("loser_party", "loser_candidate")

all2 <- full_join(winners2, losers2, by="electionname")

all2 <- all2[order(all2$electionname),]

all2$country <- sapply(1:nrow(all2), function(p){
  strsplit(all2$electionname[p], "_")[[1]][1]
})
all2$year <- sapply(1:nrow(all2), function(p){
  strsplit(all2$electionname[p], "_")[[1]][2]
})

all2 <- all2[,c(6,7,2,3,4,5)]

# table C.1
stargazer(t(t(all2[,1:4])), rownames = FALSE)

# table C.2
stargazer(t(t(all2[,c(1,2,5,6)])), rownames = FALSE)
